import datetime
import calendar
import time
from datetime import date
import cPickle

calendar.setfirstweekday(calendar.SUNDAY)

def getKey(year, month, day):
    return day+100*(month+100*year)

class SimpleCalendar:
    def __init__(self, filename=None):
        self.filename = filename
        self.cal_dict = {}
        if (filename is not None):
            try:
                f = open(filename,"rb")
                self.cal_dict = cPickle.Unpickler(f).load()
                f.close()
                if type(self.cal_dict) != type({}):
                   raise TypeError("Invalid Calendar File")
            except Exception as e:
                print 'Error loading file:', e, '- defaulting to empty calendar'
                self.cal_dict = {}
                self.filename = "default.cal"


    def load(self, filename):
        self.filename = filename
        try:
            f = open(filename,"rb")
            d = cPickle.Unpickler(f).load()
            f.close()
            if type(d) != type({}):
                raise TypeError("Invalid Calendar File")
            self.cal_dict = d
        except Exception as e:
            print 'Error loading file:', e

    def save(self, filename = None):
        if(filename is not None):
            self.filename = filename
        try:
            f = open(self.filename,"wb")
            cPickle.Pickler(f,-1).dump(self.cal_dict)
            f.close()
        except Exception as e:
            print "Failed to save:", e

    def set(self, year, month, day, text):
        key = getKey(year,month,day)
        self.cal_dict[key]=text
        if (text is None) or len(text) == 0:
            self.cal_dict.pop(key)
        
    def get(self, year, month, day):
        key = getKey(year,month,day)
        if not self.cal_dict.has_key(key):
            return ""
        return self.cal_dict[key]

    def printMonth(self, year, month):
        wkday, lastday = calendar.monthrange(year,month)
        for i in range(1,lastday+1):
            print i,self.get(year,month,i)
